<template>
  <div id="app"
       v-bind:style="appDivStyle">
    <div class="context"
         ref="context">
      <div class="queryBox"
           ref="queryBox">
        <el-form :model="formQueryCondition"
                 ref="form"
                 size="mini">
          <el-row>
            <!-- 查询条件 -->
            <!-- 标题名称 -->
            <el-col :span="5">
              <el-form-item :label="$t('AnnouncementManagement.queryLabel.announcementName')"
                            :label-width="queryformLabelWidth">
                <el-input v-model.trim="formQueryCondition.announcementTitle.val"
                          class="queryItemStyle"
                          clearable
                          :placeholder="$t('User.queryLabel.placeholderLoginName')"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item :label="$t('AnnouncementManagement.queryLabel.announcementStatus')"
                            :label-width="queryformLabelWidth">
                <el-select v-model="formQueryCondition.isEnable.val"
                           class="queryItemStyle">
                  <el-option :label="$t('label.all')"
                             value=""></el-option>
                  <el-option :value="drug.valueCode"
                             :key="drug.valueCode"
                             :label="drug.valueText"
                             v-for="drug in enables"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 列表上的按钮 -->
          <el-row>
            <el-col :span="24">
              <div style="text-align:right">
                <el-form-item>
                  <!-- 新增 -->
                  <el-button v-permission="{menuCode: menuCode, resourceCode: 'saveBtnText'}"
                             type="primary"
                             v-if="test('onNewBtn')"
                             @click="onNew('saveBtnText')">{{ $t('btnText.newBtnText') }}</el-button>

                  <!-- 重置 -->
                  <el-button v-permission="{menuCode: menuCode, resourceCode: 'resetBtnText'}"
                             type="primary"
                             @click="onReset('form')">{{ $t('btnText.resetBtnText') }}</el-button>

                  <!-- 查询 -->
                  <el-button v-permission="{menuCode: menuCode, resourceCode: 'queryBtnText'}"
                             type="primary"
                             @click="onQuery('queryBtnText')"
                             icon="el-icon-search"
                             :loading="loading">{{ $t('btnText.queryBtnText') }}</el-button>
                </el-form-item>
              </div>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="dataBox"
           ref="dataBox">

        <transition enter-active-class="animated zoomIn"
                    leave-active-class="animated rotateOut">
          <el-table v-if="isInit"
                    ref="singleTable"
                    :data="tableData"
                    :height="tableHeight"
                    @sort-change="sortChange"
                    v-loading="loading"
                    size="mini"
                    style="width: 100%;"
                    stripe=stripe
                    border=border>
            <!--序号-->
            <el-table-column type="index"
                             width="50"
                             fixed="left"
                             :label="$t('table.xh')"
                             align="center">
            </el-table-column>

            <!--操作-->
            <el-table-column :label="$t('table.op')"
                             fixed="left"
                             min-width="180">
              <template slot-scope="scope">
                <!--编辑-->
                <el-button size="gv"
                           icon="el-icon-edit"
                           :loading="loading"
                           @click="edit(scope.$index, scope.row,'editBtnText')"
                           v-permission="{menuCode: menuCode, resourceCode: 'editBtnText'}">{{ $t('btnText.editBtnText') }}</el-button>
                <!--删除按钮-->
                <el-button size="gv"
                           icon="el-icon-delete"
                           v-permission="{menuCode: menuCode, resourceCode: 'delBtnText'}"
                           type="danger"
                           :loading="loading"
                           @click="deleteRow(scope.$index, scope.row, 'delBtnText')"
                           v-show="scope.row.isEnable=='Invalid'">{{ $t('btnText.deleteBtnText') }}</el-button>
                <!-- 恢复按钮 -->
                <el-button size="gv"
                           icon="el-icon-delete"
                           v-permission="{menuCode:menuCode,resourceCode:'recoveryBtnText'}"
                           type="danger"
                           :loading="loading"
                           @click="recovery(scope.$index, scope.row,'recoveryBtnText')"
                           v-show="scope.row.isEnable=='Invalid'">{{ $t('btnText.recoveryBtnText') }}</el-button>
                
                <!--注销按钮-->
                <el-button size="gv"
                           icon="el-icon-delete"
                           v-permission="{menuCode: menuCode, resourceCode: 'passBtnText'}"
                           type="danger"
                           :loading="loading"
                           @click="logoffRow(scope.$index, scope.row, 'passBtnText')"
                           v-show="scope.row.isEnable=='Available'">{{ $t('btnText.logoffBtnText') }}</el-button>
              </template>
            </el-table-column>

            <!--公告标题-->
            <el-table-column prop="announcementTitle"
                             min-width="210"
                             fixed="left"
                             :label="$t('AnnouncementManagement.table.announcementName')"
                             sortable="custom"
                             sort-by="announcementTitle">
            </el-table-column>
            <!--公告内容-->
            <el-table-column prop="announcementContent"
                             min-width="210"
                             fixed="left"
                             :label="$t('AnnouncementManagement.table.announcementContent')"
                             sortable="custom"
                             sort-by="announcementContent">
            </el-table-column>
          </el-table>
        </transition>

      </div>
    </div>
    <div class="pageBox">
      <el-pagination @size-change="sizeChange"
                     @current-change="currentPageChange"
                     :current-page="pager.curPage"
                     :page-sizes="pager.sizes"
                     :page-size="pager.curSize"
                     :background="true"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="pager.total">
      </el-pagination>
    </div>

    <!--编辑对话框-->
    <transition enter-active-class="animated rotateIn"
                leave-active-class="animated rotateOut">
      <el-dialog :title="$t('label.dialogTitle')"
                 :visible.sync="isShowEditForm"
                 top="5vh"
                 :close-on-click-modal="false">
        <el-form :model="editForm"
                 ref="editForm"
                 size="mini"
                 :label-position="editFormPosition"
                 status-icon=status-icon
                 :rules="editRules">
          <el-input v-model.trim="editForm.keyId"
                    v-show="false"></el-input>
          <el-form-item :label="$t('AnnouncementManagement.editLabel.announcementName')"
                        :label-width="editformLabelWidth"
                        prop="announcementTitle">
            <el-input v-model.trim="editForm.announcementTitle"
                      maxlength="20"
                      :disabled="canEditCode"
                      :placeholder="$t('AnnouncementManagement.editLabel.announcementNameBs')"></el-input>
          </el-form-item>
          <el-form-item :label="$t('AnnouncementManagement.editLabel.announcementContent')"
                        :label-width="editformLabelWidth"
                        prop="announcementContent">
            <el-input v-model.trim="editForm.announcementContent"
                      maxlength="50"
                      :placeholder="$t('AnnouncementManagement.editLabel.announcementContentBs')"></el-input>
          </el-form-item>

          <el-form-item :label="$t('label.isEnabled')"
                        :label-width="editformLabelWidth">
            <el-select v-model="editForm.isEnable">
              <el-option :value="drug.valueCode"
                         :key="drug.valueCode"
                         :label="drug.valueText"
                         v-for="drug in enables"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer">
          <el-button size="mini"
                     @click="isShowEditForm = false"
                     :loading="loading">{{ $t('btnText.cancelBtnText') }}</el-button>
          <el-button size="mini"
                     type="primary"
                     @click="submitForm('editForm',currentResCode)"
                     :loading="loading">{{ $t('btnText.saveBtnText') }}</el-button>
        </div>
      </el-dialog>
    </transition>

  </div>

</template>

<script>

import comBaseVue from '../../baseViewModel';
import { isLettersNumbers, isPassword, validatePhone, validateEMail } from "../../../util/validator.js";

export default {
  mixins: [comBaseVue],
  name: 'User',
  props: {
    menuCode: String
  },
  data () {

    return {
      isShowSelectForm: false,
      isShowSelectForm2: false,
      isInit: false,
      tableHeight: 100,
      appDivStyle: {
        height: this.$store.getters.appHeight,
      },
      enables: [],
      modelName: "com.ispr.iptv.entity.sys.AnnouncementManagement",
      // 查询条件
      formQueryCondition: {
        announcementTitle: {
          key: 'announcementTitle',
          op: 'LIKE', // 操作符
          val: '' // 查询的值
        },
        isEnable: {
          key: 'isEnable',
          op: '=', // 操作符
          val: 'Available'
        },
      },

      // 编辑面板绑定的对象
      editForm: {
        keyId: 0,
        version: 0,
        announcementTitle: "",
        announcementContent: "",
        isEnable: "Available"
      },
      // 编辑面板的验证规则
      editRules: {
        announcementTitle: [{ required: true, message: this.$i18n.t('AnnouncementManagement.rules.announcementNameBs'), trigger: 'blur' }],
        announcementContent: [{ required: true, message: this.$i18n.t('AnnouncementManagement.rules.announcementContentBs'), trigger: 'blur' }],
      },
      userId: "",//授权操作的用户ID
      roles: [],//可授权的角色信息
      userRoles: [],//用户已授权的角色，用于回显
      speAreas: [],//可授权的专区
      userSpeAreas: [],//用户已授权的专区，用于回显
      checkList2: [],

    }
  },
  methods: {
    //格式化表格数据
    formatter: function (row, column, cellValue, index) {
      if (cellValue != null && cellValue != "" && cellValue.length > 15) {
        return cellValue.substr(0, 15) + "...";
      }
      return cellValue;
    },
    test: function (btnCode) {
      return true;
    },
    // 新增
    onNew: function (rescode) {
      this.currentResCode = (rescode && rescode !== '') ? rescode : '';
      this.isShowEditForm = true;
      if (this.$refs['editForm']) {
        this.$refs['editForm'].resetFields();
      }
      this.editForm.keyId = "";
      this.editForm.announcementTitle = "";
      this.editForm.announcementContent = "";
      this.curCommand = "SaveNewReturnPK";
      this.canEditCode = false;
    },

    // 重置
    onReset: function () {
      if (this.$refs['form']) {
        this.$refs['form'].resetFields();
      }
      this.formQueryCondition.announcementTitle.val = "";
      this.formQueryCondition.isEnable.val = "Available";
    },

    // 为状态下拉框赋值
    findEnables: function () {
      this.findByTypeCode("10001", this.setEnables)
    },
    // 查询状态下拉框数据成功后的回调
    setEnables: function (isSuccess, json) {
      try {
        if (isSuccess) {
          this.enables = [];
          for (var i = 0; i < json.data.length; i++) {
            this.enables.push(json.data[i]);
          }
        }
        else {
          this.$message.error(json.msg);
        }
      }
      catch (e) {
        alert(e);
      }
    },



    //角色授权提交
    submitRoleAuthorize: function (rescode) {
      this.currentResCode = (rescode && rescode !== '') ? rescode : '';
      var requestArgs = {
        commandCode: "SysUserRoleSave",
        className: this.modelName,
        commandArgs: "Default",
        commandBody: { "keyId": this.keyId, "roleList": this.userRoles },
        userInfo: this.getUserInfo()
      };
      let headersObj = {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + this.getUserInfo().tokenCode,
        'X-AOHO-UserId': this.getUserInfo().keyID
      };
      if (this.isExistResourceCode(this)) {
        headersObj['X-AOHO-Resource'] = this.menuCode + ',' + this.currentResCode;
      };
      var _this = this;
      this.axios.post('/api/execute',
        requestArgs, { headers: this.headersObj })
        .then(function (res) {
          if (res.data.code == "SUCCESS") {
            _this.isShowSelectForm = false;
            _this.$message({ message: _this.$i18n.t("message.successTip"), type: 'success' });
            _this.onQuery();
          } else {
            _this.$message({ message: res.data.msg, type: 'warning' });
          }
        })
        .catch(function (error) {
          console.log(error);
          _this.$message({ message: _this.$i18n.t("errorCode." + "serverError"), type: 'warning' });
        });
    },
    ////////////////////////////////////////////////////////角色授权结束////////////////////////////////////////////////

    ////////////////////////////////////////////////////////专区授权开始////////////////////////////////////////////////
    // 专区授权按钮单击事件
    async speAreaAuthorize (index, row, rescode) {
      this.currentResCode = (rescode && rescode !== '') ? rescode : '';
      this.keyId = row.keyId;
      await this.setSpeArea();
      this.isShowSelectForm2 = true;
      var _this = this;
      var queryRequest = {
        className: "com.ispr.iptv.entity.sys.UserSpeAreaEntity",
        opKey: "UserSpeAreas",
        params: [
          { "key": "userId", "op": "=", "val": row.keyId },
          { "key": "isEnable", "op": "=", "val": "Available" }
        ],
        userInfo: this.getUserInfo()
      };
      // let headersObj = {
      //     'Content-Type': 'application/json',
      //     'Authorization': 'Bearer ' + this.getUserInfo().tokenCode,
      //     'X-AOHO-UserId': this.getUserInfo().keyID
      //   };
      if (this.isExistResourceCode(this)) {
        this.headersObj['X-AOHO-Resource'] = this.menuCode + ',' + this.currentResCode;
      };
      //获取用户已授权的专区，并选中
      this.axios.post('/api/query', queryRequest, { headers: this.headersObj })
        .then(function (res) {
          if (res.data.code == "SUCCESS") {
            _this.userSpeAreas = [];
            for (var i = 0; i < res.data.data.length; i++) {
              _this.userSpeAreas.push(res.data.data[i].keyId);
            }
          } else {
            _this.$message.error(res.data.msg);
          }
        })
        .catch(function (error) {
          console.log(error);
          _this.$message.error(error);
        });
    },

    //专区授权提交
    submitSpeAreaAuthorize: function (rescode) {
      this.currentResCode = (rescode && rescode !== '') ? rescode : '';
      var requestArgs = {
        commandCode: "userSpeAreaAuthorize",
        className: this.modelName,
        commandArgs: "Default",
        commandBody: { "keyId": this.keyId, "speAreaList": this.userSpeAreas },
        userInfo: this.getUserInfo()
      };
      //  let headersObj = {
      //         'Content-Type': 'application/json',
      //         'Authorization': 'Bearer ' + this.getUserInfo().tokenCode,
      //         'X-AOHO-UserId': this.getUserInfo().keyID
      //       };
      if (this.isExistResourceCode(this)) {
        this.headersObj['X-AOHO-Resource'] = this.menuCode + ',' + this.currentResCode;
      };
      var _this = this;
      this.axios.post('/api/execute',
        requestArgs, { headers: this.headersObj })
        .then(function (res) {
          if (res.data.code == "SUCCESS") {
            _this.isShowSelectForm2 = false;
            _this.$message({ message: _this.$i18n.t("message.successTip"), type: 'success' });
            _this.onQuery();
          } else {
            _this.$message({ message: _this.$i18n.t("errorCode." + res.data.msg), type: 'warning' });
          }
        })
        .catch(function (error) {
          console.log(error);
          _this.$message({ message: _this.$i18n.t("errorCode." + "serverError"), type: 'warning' });
        });
    },
    ////////////////////////////////////////////////////////专区授权结束////////////////////////////////////////////////

    // 编辑按钮回调事件
    editCallback: function (isSuccess, json) {
      if (isSuccess) {
        //this.curCommand = "UpdateProc";
        this.curCommand = "PartialUpdateProc";
        this.isShowEditForm = true;
        if (this.$refs['editForm']) {
          this.$refs['editForm'].resetFields();
        }
        //this.editForm = json;
        this.editForm.keyId = json.keyId;
        this.editForm.announcementTitle = json.announcementTitle;
        this.editForm.announcementContent = json.announcementContent;
        this.editForm.isEnable = json.isEnable;
        this.editForm.version = json.version;
      }
      else {
        this.$message({
          message: json.msg,
          type: 'warning'
        });
      }
    },

    //编辑面板提交后调用，设置唯一性验证条件
    setEditFormCheck: function setEditFormCheck () {
      if (this.curCommand == "SaveNew") {
        this.editFormCheck = [{
          key: 'announcementTitle',
          op: '=', // 操作符
          val: this.editForm.announcementTitle// 查询的值
        }, {
          key: 'isEnable',
          op: '=', // 操作符
          val: 'Available'
        }];
      } else if (this.curCommand == "PartialUpdateProc") {
        this.editFormCheck = [{
          key: 'announcementTitle',
          op: '=', // 操作符
          val: this.editForm.announcementTitle// 查询的值
        }, {
          key: 'isEnable',
          op: '=', // 操作符
          val: 'Available'
        }, {
          key: 'keyId',
          op: '<>', // 操作符
          val: this.editForm.keyId
        }];
      }

    },
    //恢复按钮
    recovery: function (index, row, rescode) {
      this.currentResCode = (rescode && rescode !== '') ? rescode : '';
      var _this = this;
      this.$confirm(this.$i18n.t("message.confirmNormalMessage"),
        this.$i18n.t("message.confirmTitle"), {
        confirmButtonText: this.$i18n.t("message.yes"),
        cancelButtonText: this.$i18n.t("message.cancel"),
        type: "warning",
        callback: function (action, instance) {
          if (action == "confirm") {
            var commandBody = { "keyId": row.keyId, "version": row.version, isEnable: "Available" };
            _this.loading = true;
            _this.procCommand("RecoveryProc",
              _this.modelName,
              "default",
              commandBody,
              null,
              _this.submitFormCallback);
          }

        }
      });
    },

    //删除
    deleteRow: function (index, row, rescode) {
      this.currentResCode = (rescode && rescode !== '') ? rescode : '';
      var _this = this;
      this.$confirm(this.$i18n.t("message.confirmDelMessage"),
        this.$i18n.t("message.confirmTitle"), {
        confirmButtonText: this.$i18n.t("message.yes"),
        cancelButtonText: this.$i18n.t("message.cancel"),
        type: "warning",
        callback: function (action, instance) {
          if (action == "confirm") {
            var commandBody = { "keyId": row.keyId, "version": row.version };
            _this.loading = true;
            _this.procCommand("DelProc",
              _this.modelName,
              "default",
              commandBody,
              null,
              _this.submitFormCallback);
          }

        }
      });
    },

    exportMaterial: function exportMaterial (rescode) {
      this.currentResCode = (rescode && rescode !== '') ? rescode : '';
      let param = { 'className': 'com.ispr.iptv.entity.sys.SysUser', 'opKey': 'Export', 'params': this.queryObjToArray(this.formQueryCondition), 'sort': [{ 'col': 'keyId', 'order': 'desc' }], 'fileName': '调配资材' };
      let fileName = '系统用户信息' + '.xlsx';
      this.downloadByIdOrName(this, '/file/export', 'param', JSON.stringify(param), fileName);
    },

    //加载可授权的角色信息
    setRole: function (index, row) {
      var _this = this;
      var queryRequest = {
        className: "com.ispr.iptv.entity.sys.SysRole",
        opKey: "Roles",
        params: [{ "key": "isEnable", "op": "=", "val": "Available" }],
        userInfo: this.getUserInfo()
      };
      //查询可以授权的所有角色信息
      this.axios.post('/api/query', queryRequest, { headers: this.headersObj })
        .then(function (res) {
          if (res.data.code == "SUCCESS") {
            _this.roles = [];
            for (var i = 0; i < res.data.data.length; i++) {
              _this.roles.push(res.data.data[i]);
            }
          } else {
            _this.$message.error(res.data.msg);
          }
        })
        .catch(function (error) {
          console.log(error);
          _this.$message.error(error);
        });
    },
    //加载可授权的专区信息
    setSpeArea: function (index, row) {
      var _this = this;
      var queryRequest = {
        className: "com.ispr.iptv.entity.sys.SpeArea",
        opKey: "SpeArea",
        params: [{ "key": "isEnable", "op": "=", "val": "Available" }],
        userInfo: this.getUserInfo()
      };
      //查询可以授权的所有角色信息
      return new Promise((resolve, reject) => {
        this.axios.post('/api/query', queryRequest, { headers: this.headersObj })
          .then(function (res) {
            if (res.data.code == "SUCCESS") {
              _this.speAreas = [];
              for (var i = 0; i < res.data.data.length; i++) {
                _this.speAreas.push(res.data.data[i]);
              }
            } else {
              _this.$message.error(res.data.msg);
            }
            resolve(_this.speAreas);
          })
          .catch(function (error) {
            console.log(error);
            _this.$message.error(error);
          });
      });

      // this.axios.post('/api/query', queryRequest, {headers: this.headersObj})
      //     .then(function(res) {
      //         if (res.data.code == "SUCCESS") {
      //             _this.speAreas = [];
      //             for (var i = 0; i < res.data.data.length; i++) {
      //                 _this.speAreas.push(res.data.data[i]);
      //             }
      //         } else {
      //             _this.$message.error(_this.$i18n.t("errorCode." + json.reason,json.message));
      //         }
      //     })
      //     .catch(function(error) {
      //         console.log(error);
      //         _this.$message.error(_this.$i18n.t("errorCode." + json.reason,json.message));
      //     });
    },
    enterDown(){
      var g = this
      if(g.isShowEditForm){
        g.submitForm('editForm',g.currentResCode)
      }else if(!g.loading){
        g.onQuery()
      }
    }
  },
  mounted: function mounted () {
    this.findEnables();
    this.setRole();
    this.setSpeArea();
    this.tableHeight = this.$refs.context.offsetHeight - this.$refs.queryBox.offsetHeight;
    this.isInit = true;
    this.formQueryCondition.isEnable.val = "Available";
    this.onQuery();

  }
}


</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.el-checkbox {
  width: 120px;
  margin: 10px 0;
  margin-left: 30px;
}
</style>
